<?php

class ImageManager
{
    var $url;
    var $image;
    var $data;
    
    function __construct($url)
    {
        if (strlen($url)) self::load($url);
    }
    
    function load($url)
    {
        $this->url = $url;
        $this->data = file_get_contents($url);
        $this->image = imagecreatefromstring($this->data);
    }
    
    function resize($maxwidth, $maxheight, $r = 255, $g = 255, $b = 255)
    {
        $width = imagesx($this->image);
        $height = imagesy($this->image);
        
        if ($width > $height)
        {
          $delta = $width/$maxwidth;
          $new_height = intval(ceil($height/$delta));
          $new_width = $maxwidth;
          
          $dy = floor(($maxheight-$new_height)/2);     
        }
        else if ($height >= $width)
        {
          $delta = $height/$maxheight;
          $new_width = intval(ceil($width/$delta));
          $new_height = $maxheight;    
          
          $dx = floor(($maxwidth-$new_width)/2);     
        }
        else
        {
            $new_width = $maxwidth;
            $new_height = $maxheight;
        }
        
        $image_resized = imagecreatetruecolor($maxwidth, $maxheight);
        $color = imagecolorallocate($image_resized, $r, $g, $b);
        imagefilledrectangle($image_resized, 0, 0, $maxwidth, $maxheight, $color);
        imagecopyresampled($image_resized, $this->image, $dx, $dy, 0, 0, $new_width, $new_height, $width, $height);
        $this->image = $image_resized;
        echo 'x:'.imagesx($this->image);
    }
    
    function save($path)
    {
        imagejpeg($this->image, $path);
    }
}

?>